package com.rambo.map;

import com.amap.api.maps.*;
import com.amap.api.maps.model.*;
import com.rambo.baselib.constant.ParamConstant;
import com.rambo.baselib.fraction.BaseFraction;
import com.rambo.baselib.mvp.BasePresenter;
import com.rambo.baselib.util.GpsUtil;
import com.rambo.baselib.util.LogUtil;
import com.rambo.baselib.util.ToastUtil;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.location.Location;
import ohos.location.Locator;
import ohos.location.LocatorCallback;
import ohos.location.RequestParam;

/**
 * The dependencies of the local HAR file are not supported during HAR building because the classes and
 * HarmonyOS resources in the local HAR file dependencies are not packaged in the generated HAR.
 * <p>
 * 解决办法：https://developer.harmonyos.com/cn/docs/documentation/doc-guides/faq-compiling-and-building-0000001240620261#section168665591512
 * <p>
 * <p>
 * <p>
 * 地图
 */
public class MapFraction extends BaseFraction implements LocationSource, LocatorCallback {
    public static String KEY = "您的KEY";
    MapView mapView;
    AMap aMap;
    Locator locator;
    OnLocationChangedListener mListener;

    public MapFraction(Context context) {
        super(context);
    }

    @Override
    protected int getLayoutResId() {
        return ResourceTable.Layout_fraction_map;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Component component) {
        super.initView(component);
        if (component instanceof ComponentContainer) {
            mapView = new MapView(getFractionAbility());
            ((ComponentContainer) component).addComponent(mapView,
                    new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT));
        }
//        mapView = (MapView) component.findComponentById(ResourceTable.Id_map_view);
        verifyLocationPermission();
    }

    /**
     * 校验定位权限
     */
    public void verifyLocationPermission() {
        if (mapView == null) return;
        if (verifySelfPermission(ParamConstant.PERMISSION_LOCATION) != IBundleManager.PERMISSION_GRANTED) {
            if (canRequestPermission(ParamConstant.PERMISSION_LOCATION)) {
                requestPermissionsFromUser(new String[]{ParamConstant.PERMISSION_LOCATION}, ParamConstant.PERMISSION_LOCATION_CODE);
            }
        } else {
            if (aMap == null) {
                MapsInitializer.setApiKey(KEY);
                mapView.onCreate(null);
                mapView.onResume();
                aMap = mapView.getMap();
                aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                    @Override
                    public void onMapLoaded() {
                        setUpMap();
                    }
                });

            }
            if (locator == null) {
                startLocator();
            }
        }
    }

    private void startLocator() {
        locator = new Locator(context);
        RequestParam requestParam = new RequestParam(RequestParam.PRIORITY_FAST_FIRST_FIX, 5, 0);
        locator.startLocating(requestParam, this);
    }

    Marker marker;
    //当点击地图或者其他操作，离开当前用户定位位置时，用这个标志来判断，不要更新当前视图，避免用户操作无效
    boolean isLocation = true;

    private void setUpMap() {
        aMap.setLocationSource(this);
        //显示定位按钮
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        //所有手势可用
        aMap.getUiSettings().setAllGesturesEnabled(true);
        //中心点缩放
        aMap.getUiSettings().setGestureScaleByMapCenter(true);
        //双指缩放可用
        aMap.getUiSettings().setZoomGesturesEnabled(true);
        //缩放按钮不可见
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //指南针可见
        aMap.getUiSettings().setCompassEnabled(true);
        //室内图层切换可见
        aMap.getUiSettings().setIndoorSwitchEnabled(true);
        //倾斜手势可用
        aMap.getUiSettings().setTiltGesturesEnabled(true);
        //比例尺可见
        aMap.getUiSettings().setScaleControlsEnabled(true);
        //logo 位置
//        aMap.getUiSettings().setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_CENTER);
        aMap.setMyLocationEnabled(true);
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                isLocation = true;
                LogUtil.e("====onMyLocationChange===");
            }
        });
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                isLocation = false;
                ToastUtil.toast("===onMapClick==");
                if (marker != null) {
                    LatLng position = marker.getPosition();
                    if (position.latitude == latLng.latitude && position.longitude == latLng.longitude) {
                        return;
                    }
                    marker.hideInfoWindow();
                    marker.destroy();
                    marker = null;
                }
                MarkerOptions markerOption = new MarkerOptions()
                        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                        .displayLevel(5)
                        .position(latLng)
                        .title("到这里")
                        .snippet("latLng.")
                        .draggable(false);
                marker = aMap.addMarker(markerOption);
                marker.showInfoWindow();
            }
        });
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                ToastUtil.toast("===onMarkerClick==");
                isLocation = false;
                //TODO 这里打算点击标志后，实现搜索规划路径到达该目的，然后在实现跨设备迁移流转操作
                return true;
            }
        });
        aMap.setAMapGestureListener(new AMapGestureListener() {
            @Override
            public void onDoubleTap(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onSingleTap(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onFling(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onScroll(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onLongPress(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onDown(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onUp(float v, float v1) {
                isLocation = false;
            }

            @Override
            public void onMapStable() {
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapView.onDestroy();
        mListener=null;
        if (locator != null) {
            locator.stopLocating(this);
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        this.mListener = onLocationChangedListener;
        if (locator == null) {
            startLocator();
        }
    }

    @Override
    public void deactivate() {
        if (locator != null) {
            locator.stopLocating(this);
        }
    }

    @Override
    public void onLocationReport(Location location) {
        if (location != null && mListener != null) {
            Location location1 = GpsUtil.toGdMapGps(location);
            if (isLocation) {
                mListener.onLocationChanged(location1);
            }
        }
    }

    @Override
    public void onStatusChanged(int i) {

    }

    @Override
    public void onErrorReport(int i) {

    }
}
